package com.zj;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Task implements Runnable{
    private Socket socket;
    private Handle handle;
    private boolean flag;
    public Task(Socket socket,Handle handle){
        this.socket=socket;
        this.handle=handle;
        this.flag=true;
    }

    @Override
    public void run() {
        try(
                //因为要用到try...resource 直接关闭socket 所以需要将socket 重新在try注册
                Socket s=this.socket;
                Scanner reader=new Scanner(s.getInputStream());
                PrintWriter writer=new PrintWriter(s.getOutputStream());  //包装成字符流
        ){
            //线程中止判断 flag业务中止判断  Thread.currentThread().isInterrupted() 线程中止判断
            while(flag && !Thread.currentThread().isInterrupted()){
                //客户端是否没有传数据,如没有传,则结束
                if(!reader.hasNext()){
                    System.out.println("学生端"+s.getRemoteSocketAddress()+"断开连接");
                    break;
                }
                //如果有数据,则读取
                String command=reader.nextLine();  //取出一整行
                //命令模式 :
                if ("screenshot".equalsIgnoreCase(command)){
                    //1.学生端截图 screenshot
                    handle.screenshot(socket);
                }else if("shutdown".equalsIgnoreCase(command)){
                    //2.学生端关机 shutdown
                    System.out.println("学生端"+s.getRemoteSocketAddress()+"请求关机");
                    //线程中止
//                    Thread.currentThread().interrupt();
                    System.exit(0);
                }else if (command.toLowerCase().startsWith("sendmessage ")) {
                    //3.发送信息 sendMessage
                    //取出要发送的信息
                    String message = command.substring("sendMessage ".length()).trim();
                    handle.sendMessage(message);
                }else if("QUIT".equalsIgnoreCase(command)){
                    //断开连接
                    System.out.println("学生端"+s.getRemoteSocketAddress()+"已经被断开连接");
                    break;
                }
                writer.println("服务器端响应："+command);
                writer.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
